package com.rybbaby.tss.core.sql.metadata;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.ForeignKey;

/**
 * @description 外键元数据
 * 
 * @author 谢进伟
 *
 * @createDate 2016年2月15日 下午2:11:46
 */
public class ForeignKeyMetadata {
	
	/** 外键名称 **/
	private final String name;
	/** 外键所属表表名称 **/
	private final String refTable;
	/** 外键集合，key 为refTable表列名小写，value 为引用表列名 **/
	private final Map<String , String> references = new HashMap<String , String>();
	
	public ForeignKeyMetadata (ResultSet rs ) throws SQLException{
		name = rs.getString("FK_NAME");
		refTable = rs.getString("PKTABLE_NAME");
	}
	
	public String getName() {
		return name;
	}
	
	public String getReferencedTableName() {
		return refTable;
	}
	
	void addReference(ResultSet rs) throws SQLException {
		references.put(rs.getString("FKCOLUMN_NAME").toLowerCase(Locale.ROOT) , rs.getString("PKCOLUMN_NAME"));
	}
	
	private boolean hasReference(Column column , Column ref) {
		String refName = (String)references.get(column.getName().toLowerCase(Locale.ROOT));
		return ref.getName().equalsIgnoreCase(refName);
	}
	
	public boolean matches(ForeignKey fk) {
		if(refTable.equalsIgnoreCase(fk.getReferencedTable().getName())) {
			if(fk.getColumnSpan() == references.size()) {
				List<?> fkRefs;
				if(fk.isReferenceToPrimaryKey()) {
					fkRefs = fk.getReferencedTable().getPrimaryKey().getColumns();
				} else {
					fkRefs = fk.getReferencedColumns();
				}
				for(int i = 0 ; i < fk.getColumnSpan() ; i++) {
					Column column = fk.getColumn(i);
					Column ref = (Column)fkRefs.get(i);
					if(!hasReference(column , ref)) {
						return false;
					}
				}
				return true;
			}
		}
		return false;
	}
	
	public Map<String , String> getReferences() {
		return references;
	}
	
	public String toString() {
		return "ForeignKeyMetadata(" + name + ')';
	}
}
